from microbit import *
import oled12864_i2c

# 判断方向函数，输入2个int，j是方向，ab是按下A或B
# 输出一个int，函数名判断方向
def pdfx(j, ab):
    # 如果按下的是A键
    if ab == 1:
        # 如果朝东
        if j == 1:
            j = 2
        # 如果朝南
        elif j == 2:
            j = 3
        # 如果朝西
        elif j == 3:
            j = 4
        # 否
        else:
            j = 1
    else:
        # 如果朝东
        if j == 1:
            j = 4
        # 如果朝南
        elif j == 2:
            j = 1
        # 如果朝西
        elif j == 3:
            j = 2
        # 否
        else:
            j = 3
    return j


oled = oled12864_i2c.OLED12864_I2C()
oled.clear()

oled.zoom(0)
oled.rect(0, 0, 127, 63)
snake = [(10, 10), (11, 10), (12, 10), (13, 10), (14, 10)]
for a in snake:
    oled.pixel(a[0], a[1], 1)
# 定义变量x，y
x = 10
y = 10
j = 1
# 一直循环
while True:
    # 如果按下A
    if button_a.was_pressed():
        j = pdfx(j, 1)
    elif button_b.was_pressed():
        j = pdfx(j, 2)

    # 如果该朝东
    if j == 1:
        x += 1
    # 如果该朝南
    elif j == 2:
        y += 1
    # 如果该朝西
    elif j == 3:
        x -= 1
    # 如果该朝北
    else:
        y -= 1
    sleep(100)
    for a in snake:
        oled.pixel(a[0], a[1], 0)
    # 删除第4个元组
    del snake[len(snake) - 1]
    # 在第0位插入新元组
    snake.insert(0, (x, y))
    for a in snake:
        oled.pixel(a[0], a[1], 1)
    if x == 127:
        break
    elif x == 1:
        break
    elif y == 1:
        break
    elif y == 63:
        break
